package com.nanrui.mutualinductor.ui.page;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.batman.baselibrary.Constant;
import com.batman.baselibrary.db.RtBean;
import com.batman.baselibrary.utils.TimeUtils;
import com.batman.baselibrary.utils.TipDialogUtils;
import com.batman.baselibrary.utils.ToastUtils;
import com.google.gson.Gson;
import com.nanrui.mutualinductor.R;
import com.nanrui.mutualinductor.communicate.PacketCallback;
import com.nanrui.mutualinductor.data.CTCheckData;
import com.nanrui.mutualinductor.data.CheckData;
import com.nanrui.mutualinductor.data.DKPacket;
import com.nanrui.mutualinductor.data.DKPowerData;
import com.nanrui.mutualinductor.data.Packet_57_01;
import com.nanrui.mutualinductor.domains.PTTraditionTransformerViewInfo;
import com.nanrui.mutualinductor.ui.service.PTTraditionTransformerService;
import com.nanrui.mutualinductor.ui.widget.CustomTitleDialog;
import com.ui.widget.CustomOnessDialog;
import com.ui.widget.UINavigationView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class PTTraditionActivity extends DKActivity {

    @BindView(R.id.uinv)
    UINavigationView mUinv;
    @BindView(R.id.et_person)
    EditText mEtPerson;
    @BindView(R.id.et_property_id)
    EditText mEtPropertyId;
    @BindView(R.id.et_position)
    EditText mEtPosition;
    @BindView(R.id.et_rated_electricity)
    TextView mEtRatedElectricity;
    @BindView(R.id.tv_rated_electricity_two)
    TextView mTvRatedElectricityTwo;
    @BindView(R.id.tv_level)
    TextView mTvLevel;
    @BindView(R.id.tv_coso)
    EditText mTvCoso;
    @BindView(R.id.et_rated_load)
    EditText mEtRatedLoad;

    @BindView(R.id.tv_floor_load)
    EditText mTvFloorLoad;

    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.btn_measure)
    Button mBtnMeasure;
    @BindView(R.id.btn_start)
    Button mBtnStart;
    @BindView(R.id.btn_exit)
    Button mBtnExit;


    @BindView(R.id.tv_result_key)
    TextView mTvResultKey;
    @BindView(R.id.tv_result)
    TextView mTvResult;
    @BindView(R.id.ll_data)
    LinearLayout mLlData;

    @BindView(R.id.btn_save)
    Button mBtnSave;

    @BindView(R.id.ll_do_not)
    LinearLayout ll_do_not;

    @BindView(R.id.et_test_company)
    EditText etTestCompany;
    @BindView(R.id.et_made_company)
    EditText etMadeCompany;
    @BindView(R.id.et_task_number)
    EditText etTaskNumber;

    @BindView(R.id.device_name_tv)
    EditText deviceNameTv;
    @BindView(R.id.device_type_tv)
    EditText deviceTypeTv;

    private PTTraditionTransformerService service;
    private Timer timer;
    private PTTraditionTransformerViewInfo viewInfo;

    List<CTCheckData> ydata;

    @Override
    protected void onStop() {
        if (this.timer != null) {
            this.timer.cancel();
            this.timer.purge();
        }
        super.onStop();
    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_pt_tradition;
    }

    @Override
    public void initViews() {

        ll_do_not.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        ydata = new ArrayList<>();
        mUinv.setNavigationTitle("PT传统法误差测试");
        mTvDate.setText("时间：" + TimeUtils.date2String(new Date(), new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())));


        mEtRatedElectricity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomTitleDialog dialog = new CustomTitleDialog(mContext);

                dialog.subTvTitle.setText("额定一次");
                if (viewInfo.getmRatedSecondary() == 100.0F) {
                    dialog.setData(Arrays.asList(DKPowerData.PT_1ND_VOLTAGE_STRING));
                } else if (viewInfo.getmRatedSecondary() == DKPowerData.PT_2ND_VOLTAGE_RADICAL_100) {
                    dialog.setData(Arrays.asList(DKPowerData.PT_1ND_VOLTAGE_RADICAL_STRING));
                } else {

                    ToastUtils.showLong("请先选择额定二次");
                    return;
                }

                dialog.mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        float data = 0;
                        if (viewInfo.getmRatedSecondary() == 100.0F) {
                            data = DKPowerData.PT_1ND_VOLTAGE_NUMBER[position];
                        }
                        if (viewInfo.getmRatedSecondary() == DKPowerData.PT_2ND_VOLTAGE_RADICAL_100) {
                            data = DKPowerData.PT_1ND_VOLTAGE_RADICAL_NUMBER[position];
                        }

                        viewInfo.setmRatedPrimary(data);

                        setView();
                        setViewInfo(viewInfo);
                        dialog.dismiss();
                    }
                });

                dialog.buttonCancel.setText("取消");
                dialog.buttonCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });

        mTvRatedElectricityTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new AlertDialog.Builder(mContext).setItems(DKPowerData.PT_2ND_VOLTAGE_STRING, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int position) {
                        dialog.dismiss();
                        float data = DKPowerData.PT_2ND_VOLTAGE_NUMBER[position];
                        viewInfo.setmRatedSecondary(data);

                        //额定一次重置为0
                        viewInfo.setmRatedPrimary(0F);

                        setView();
                        setViewInfo(viewInfo);
                    }
                }).show();
            }
        });

        mTvLevel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                CustomTitleDialog dialog = new CustomTitleDialog(mContext);

                dialog.subTvTitle.setText("精度等级");
                dialog.setData(Arrays.asList(DKPowerData.PT_GRADES_STRING));
                dialog.mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        dialog.dismiss();
                        short data = DKPowerData.PT_GRADES_NUMBER[position];
                        viewInfo.setmGrade(data);

                        setView();
                        setViewInfo(viewInfo);
                    }
                });

                dialog.buttonCancel.setText("取消");
                dialog.buttonCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();


            }
        });
    }

    @Override
    public void loadData(Bundle savedInstanceState) {

        this.service = new PTTraditionTransformerService(this);
        this.viewInfo = service.getDefaultViewInfo();
        if (Constant.isDeug) {
            viewInfo.setmGrade((short) 1);
            mBtnSave.setEnabled(true);
            setisplayViewInfo(viewInfo);
        }
        rcLocation();
    }
    @Override
    protected void locationSuccess(AMapLocation location) {
        super.locationSuccess(location);
        mEtPosition.setText(location.getAddress());
    }

    private void setView() {

        float PhaseAngle = 0f;
        try {
            PhaseAngle = Float.parseFloat(mTvCoso.getText().toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        viewInfo.setmPhaseAngle(PhaseAngle);

        //计量
        float RatedLoad = 0f;
        try {
            RatedLoad = Float.parseFloat(mEtRatedLoad.getText().toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        viewInfo.setmMeaWinRatedLoad(RatedLoad);

        float MiniLoad = 0f;
        try {
            MiniLoad = Float.parseFloat(mTvFloorLoad.getText().toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        viewInfo.setmMeaWinMiniLoad(MiniLoad);


    }

    /**
     * 填写数据
     *
     * @param info
     */
    private void setViewInfo(PTTraditionTransformerViewInfo info) {

        mEtRatedElectricity.setText(info.getMRatedPrimary());
        mTvRatedElectricityTwo.setText(info.getMRatedSecondary());

        mEtRatedLoad.setText(info.getMMeaWinRatedLoad());
        mTvFloorLoad.setText(info.getMMeaWinMiniLoad());



        mTvLevel.setText(info.getMGrade());
        mTvCoso.setText(info.getMPhaseAngle() + "");
    }

    /**
     * 返回数据
     *
     * @param info
     */
    private void setisplayViewInfo(PTTraditionTransformerViewInfo info) {

        if (ydata != null) {
            ydata.clear();
        }
        if (Constant.isDeug) {
            float[] iErrors = new float[]{-0.21f, 0.111f, -0.086f, -0.026f, -0.033f};
            viewInfo.setsUErrors(iErrors);
            float[] iRoundErrors = new float[]{-0.22f, -0.12f, -0.08f, -0.02f, -0.04f};
            viewInfo.setsURoundErrors(iRoundErrors);
            float[] sPhaseDisps = new float[]{8.6f, 10.3f, 5.8f, 1.1f, 1.1f};
            viewInfo.setsPhaseDisps(sPhaseDisps);
            float[] sPhaseRoundDisps = new float[]{1f, 10f, 6f, 1f, 1f};
            viewInfo.setsPhaseRoundDisps(sPhaseRoundDisps);

            try {
                CTCheckData ctCheckDatay;
                for (int i = 0; i < iErrors.length; i++) {

                    ctCheckDatay = new CTCheckData();
                    ctCheckDatay.names = new ArrayList<>();
                    ctCheckDatay.names.add(iErrors[i] + "");
                    ctCheckDatay.names.add(iRoundErrors[i] + "");
                    ctCheckDatay.names.add(sPhaseDisps[i] + "");
                    ctCheckDatay.names.add(sPhaseRoundDisps[i] + "");
                    ydata.add(ctCheckDatay);
                }


                for (int i = 0; i < mLlData.getChildCount(); i++) {
                    //第一层viewgroup
                    ViewGroup view1 = (ViewGroup) mLlData.getChildAt(i);

                    //第二层viewgroup
                    for (int j = 0; j < view1.getChildCount(); j++) {
                        paseFormData(i, view1, j);

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {

            String[] iErrors = info.getSUErrors();
            String[] iRoundErrors = info.getSURoundErrors();
            String[] sPhaseDisps = info.getSPhaseDisps();
            String[] sPhaseRoundDisps = info.getSPhaseRoundDisps();

            try {
                CTCheckData ctCheckDatay;
                for (int i = 0; i < iErrors.length; i++) {

                    ctCheckDatay = new CTCheckData();
                    ctCheckDatay.names = new ArrayList<>();
                    ctCheckDatay.names.add(TextUtils.isEmpty(iErrors[i]) ? "" : iErrors[i]);
                    ctCheckDatay.names.add(TextUtils.isEmpty(iRoundErrors[i]) ? "" : iRoundErrors[i]);
                    ctCheckDatay.names.add(TextUtils.isEmpty(sPhaseDisps[i]) ? "" : sPhaseDisps[i]);
                    ctCheckDatay.names.add(TextUtils.isEmpty(sPhaseRoundDisps[i]) ? "" : sPhaseRoundDisps[i]);
                    ydata.add(ctCheckDatay);
                }


                for (int i = 0; i < mLlData.getChildCount(); i++) {
                    //第一层viewgroup
                    ViewGroup view1 = (ViewGroup) mLlData.getChildAt(i);

                    //第二层viewgroup
                    for (int j = 0; j < view1.getChildCount(); j++) {
                        paseFormData(i, view1, j);

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private void paseFormData(int i, ViewGroup view1, int j) {
        ViewGroup view2 = (ViewGroup) view1.getChildAt(j);

        int index = Math.min(8, i * 3 + j);
        CTCheckData data = ydata.get(index);
        //第三层view
        boolean isRedBg = false;
        for (int k = 0; k < view2.getChildCount(); k++) {
            if (view2.getChildAt(k).getId() == R.id.tv_result) {

            } else if (view2.getChildAt(k).getId() == R.id.tv_result_key) {

            } else {


                String value = data.names.get(k);

                if (!TextUtils.isEmpty(value)) {

                    float fValue = 0F;
                    try {
                        fValue = Float.parseFloat(value);

                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }

                    float settingValueX = CheckData.ptMapXING.get(viewInfo.getmGrade())[j];
                    float settingValueB = CheckData.ptMapB.get(viewInfo.getmGrade())[j];
                    if (settingValueX == CheckData.UNKNOW_VALUE || settingValueB == CheckData.UNKNOW_VALUE) {

                    } else {
                        if (k >= 2) {
                            if (Math.abs(fValue) > settingValueX) {
                                if (!isRedBg) {
                                    isRedBg = true;
                                }
                            }
                        } else {
                            if (Math.abs(fValue) > settingValueB) {
                                if (!isRedBg) {
                                    isRedBg = true;
                                }
                            }
                        }
                    }

                    ((TextView) view2.getChildAt(k)).setText(value);

                } else {
                    ((TextView) view2.getChildAt(k)).setText("");
                }

            }


        }

        if (isRedBg) {
            for (int k = 0; k < view2.getChildCount(); k++) {
                if (view2.getChildAt(k).getId() == R.id.tv_result) {

                } else if (view2.getChildAt(k).getId() == R.id.tv_result_key) {

                } else {
                    ((TextView) view2.getChildAt(k)).setBackgroundResource(R.drawable.verification_edit_bg_red);
                }
            }
        } else {
            for (int k = 0; k < view2.getChildCount(); k++) {
                if (view2.getChildAt(k).getId() == R.id.tv_result) {

                } else if (view2.getChildAt(k).getId() == R.id.tv_result_key) {

                } else {
                    ((TextView) view2.getChildAt(k)).setBackgroundResource(R.drawable.verification_edit_bg_normal);
                }
            }
        }
    }


    @OnClick({R.id.btn_measure, R.id.btn_start, R.id.btn_exit, R.id.btn_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_measure:
                //将填写数据设置
                try {
                    setView();
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    ToastUtils.showLong("输入数据有误");
                    return;
                }

                //将表格数据清空
                service.resetResult(viewInfo);

                TipDialogUtils.showProgressDialog(mContext, "", true, new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {

                    }
                });
                this.service.updateConfig(this.viewInfo, new PacketCallback() {
                    @Override
                    public void packetReceived(DKPacket data) {
                        TipDialogUtils.dismissProgressDialog();
                        viewInfo.setmStatus((short) 1);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mBtnStart.setText(viewInfo.getMeasureStatus());
                                mBtnStart.setEnabled(true);
                                ll_do_not.setVisibility(View.GONE);
                                ToastUtils.showLong("设置成功");
                            }
                        });
                    }
                });
                break;
            case R.id.btn_start:
                if ((this.viewInfo.getmStatus() != 2) && (this.viewInfo.getmStatus() != 4)) {
                        //将填写数据设置
                        try {
                            setView();
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            ToastUtils.showLong("输入数据有误");
                            return;
                        }
                        mBtnSave.setEnabled(false);
                        ll_do_not.setVisibility(View.VISIBLE);
                        //将表格数据清空
                        this.service.resetResult(this.viewInfo);
                        setisplayViewInfo(viewInfo);
                        this.viewInfo.setmStatus((short) 2);
                        mBtnStart.setText(viewInfo.getMeasureStatus());

                        this.service.start1ndMeasure(this.viewInfo, new PacketCallback() {
                            @Override
                            public void packetReceived(DKPacket data) {

                                SystemClock.sleep(2000L);
                                timer = new Timer();
                                timer.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        service.queryData(viewInfo, new PacketCallback() {
                                            @Override
                                            public void packetReceived(DKPacket data) {


                                                Packet_57_01 paramAnonymous3Packet_57_01 = (Packet_57_01) data;
                                                if (paramAnonymous3Packet_57_01.getsStatus() == 4) {
                                                    if (timer != null) {
                                                        timer.cancel();
                                                        timer.purge();
                                                    }
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            runOnUiThread(new Runnable() {
                                                                public void run() {
                                                                    ToastUtils.showLong("检测完成");
                                                                }
                                                            });
                                                        }
                                                    });
                                                    viewInfo.setmStatus((short) 5);
                                                    viewInfo.setsResult(Short.valueOf(paramAnonymous3Packet_57_01.getsResult()));
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            service.display(viewInfo, paramAnonymous3Packet_57_01);
                                                            setisplayViewInfo(viewInfo);

                                                            ll_do_not.setVisibility(View.GONE);
                                                            mBtnStart.setText(viewInfo.getMeasureStatus());
                                                            mTvResult.setText(viewInfo.getSResult());
                                                            mBtnSave.setEnabled(true);
                                                        }
                                                    });

                                                } else if (paramAnonymous3Packet_57_01.getsFlag() == 3) {
                                                    if (paramAnonymous3Packet_57_01.getsStatus() == 0) {
                                                        if (timer != null) {
                                                            timer.cancel();
                                                            timer.purge();
                                                        }
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {

                                                                CustomOnessDialog dialog = new CustomOnessDialog(mContext);
                                                                dialog.tvTitle.setText("提醒");
                                                                dialog.subTvTitle.setText("极性错误\n请停止试验，检查接线无误后再启动试验");
                                                                dialog.subTvTitle.setVisibility(View.VISIBLE);

                                                                dialog.buttonOK.setText("确定");
                                                                dialog.buttonOK.setOnClickListener(new View.OnClickListener() {
                                                                    @Override
                                                                    public void onClick(View v) {
                                                                        dialog.dismiss();
                                                                    }
                                                                });
                                                                dialog.setCancelable(false);
                                                                dialog.show();
                                                            }
                                                        });
                                                    }
                                                    if (paramAnonymous3Packet_57_01.getsStatus() == 1) {
                                                        if (timer != null) {
                                                            timer.cancel();
                                                            timer.purge();
                                                        }
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {

                                                                CustomOnessDialog dialog = new CustomOnessDialog(mContext);
                                                                dialog.tvTitle.setText("提醒");
                                                                dialog.subTvTitle.setText("变比错误\n请停止试验，检查接线无误后再启动试验");
                                                                dialog.subTvTitle.setVisibility(View.VISIBLE);

                                                                dialog.buttonOK.setText("确定");
                                                                dialog.buttonOK.setOnClickListener(new View.OnClickListener() {
                                                                    @Override
                                                                    public void onClick(View v) {
                                                                        dialog.dismiss();
                                                                    }
                                                                });
                                                                dialog.setCancelable(false);
                                                                dialog.show();
                                                            }
                                                        });
                                                    }
                                                    if (paramAnonymous3Packet_57_01.getsStatus() == 2) {
                                                        if (timer != null) {
                                                            timer.cancel();
                                                            timer.purge();
                                                        }
                                                        runOnUiThread(new Runnable() {
                                                            public void run() {

                                                                CustomOnessDialog dialog = new CustomOnessDialog(mContext);
                                                                dialog.tvTitle.setText("提醒");
                                                                dialog.subTvTitle.setText("接线错误\n请停止试验，检查接线无误后再启动试验");
                                                                dialog.subTvTitle.setVisibility(View.VISIBLE);

                                                                dialog.buttonOK.setText("确定");
                                                                dialog.buttonOK.setOnClickListener(new View.OnClickListener() {
                                                                    @Override
                                                                    public void onClick(View v) {
                                                                        dialog.dismiss();
                                                                    }
                                                                });
                                                                dialog.setCancelable(false);
                                                                dialog.show();
                                                            }
                                                        });
                                                    }
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            service.display(viewInfo, paramAnonymous3Packet_57_01);
                                                            setisplayViewInfo(viewInfo);
                                                        }
                                                    });

                                                }
                                            }
                                        });
                                    }
                                }, 0L, 1000L);
                            }
                        });
                } else {
                    //停止
                    short s = this.viewInfo.getmStatus();
                    this.viewInfo.setmStatus((short) 1);

                    ll_do_not.setVisibility(View.GONE);
                    mBtnStart.setText(viewInfo.getMeasureStatus());
                    this.service.stopMeasure(this.viewInfo, new PacketCallback() {
                        @Override
                        public void packetReceived(DKPacket data) {
                            if (timer != null) {
                                timer.cancel();
                                timer.purge();
                            }
                        }
                    });
                }
                break;
            case R.id.btn_exit:
                finish();
                break;
            case R.id.btn_save:
                new AlertDialog.Builder(mContext).
                        setTitle("提醒")
                        .setMessage("你确定要保存吗")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                PTTraditionTransformerViewInfo localCTErrorResp = new PTTraditionTransformerViewInfo();

                                //返回 f u r
                                localCTErrorResp.setsPhaseError(viewInfo.getsPhaseError());
                                localCTErrorResp.setsQuadratureError(viewInfo.getsQuadratureError());
                                localCTErrorResp.setsPrimaryU(viewInfo.getsPrimaryU());
                                localCTErrorResp.setsSecondaryR(viewInfo.getsSecondaryR());
                                localCTErrorResp.setsDCR(viewInfo.getsDCR());
                                localCTErrorResp.setsXb(viewInfo.getsXb());

                                //tab2 g b u
                                localCTErrorResp.setsG(viewInfo.getsG());
                                localCTErrorResp.setsB(viewInfo.getsB());
                                localCTErrorResp.setsSecondaryU(viewInfo.getsSecondaryU());

                                //表格

                                localCTErrorResp.setsUErrors(viewInfo.getsUErrors());
                                localCTErrorResp.setsURoundErrors(viewInfo.getsURoundErrors());
                                localCTErrorResp.setsPhaseDisps(viewInfo.getsPhaseDisps());
                                localCTErrorResp.setsPhaseRoundDisps(viewInfo.getsPhaseRoundDisps());
                                //结果
                                localCTErrorResp.setsResult(viewInfo.getsResult());
                                //填写数据
                                localCTErrorResp.setmRatedPrimary(viewInfo.getmRatedPrimary());
                                localCTErrorResp.setmRatedSecondary(viewInfo.getmRatedSecondary());
                                localCTErrorResp.setmMeaWinRatedLoad(viewInfo.getmMeaWinRatedLoad());
                                localCTErrorResp.setmMeaWinMiniLoad(viewInfo.getmMeaWinMiniLoad());
                                localCTErrorResp.setmSurWinRatedLoad(viewInfo.getmSurWinRatedLoad());
                                localCTErrorResp.setmSurWinMiniLoad(viewInfo.getmSurWinMiniLoad());

                                localCTErrorResp.setmGrade(viewInfo.getmGrade());
                                localCTErrorResp.setmPhaseAngle(viewInfo.getmPhaseAngle());

                                //自定义数据

                                localCTErrorResp.setTime(TimeUtils.getNowString());

                                localCTErrorResp.setTestCompany(etTestCompany.getText().toString().trim());
                                localCTErrorResp.setMadeCompany(etMadeCompany.getText().toString().trim());
                                localCTErrorResp.setTaskNumber(etTaskNumber.getText().toString().trim());
                                localCTErrorResp.setDevciceName(deviceNameTv.getText().toString().trim());
                                localCTErrorResp.setDeviceType(deviceTypeTv.getText().toString().trim());
                                localCTErrorResp.setName(mEtPerson.getText().toString().trim());
                                localCTErrorResp.setNum(mEtPropertyId.getText().toString().trim());
                                localCTErrorResp.setAddress(mEtPosition.getText().toString().trim());

                                RtBean bean = new RtBean();
                                bean.type = RtBean.TYPE_2;

                                bean.person = localCTErrorResp.getName();
                                bean.num = localCTErrorResp.getNum();
                                bean.place = localCTErrorResp.getAddress();
                                bean.date = localCTErrorResp.getTime();

                                Gson gson = new Gson();
                                bean.TContent = gson.toJson(localCTErrorResp);
                                if (bean.save()) {
                                    ToastUtils.showLong("保存成功");
                                } else {
                                    ToastUtils.showLong("保存失败");
                                }
                            }
                        }).
                        show();

                break;
        }
    }


    @Override
    public void onBackPressed() {
        if (viewInfo.getIsNotRunning()) {
            new AlertDialog.Builder(mContext).
                    setTitle("提醒")
                    .setMessage("当前设备正在运行，退出前需要先停止设备")
                    .setPositiveButton("确定停止", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            service.stopMeasure(viewInfo, new PacketCallback() {
                                @Override
                                public void packetReceived(DKPacket data) {

                                    if (timer != null) {
                                        timer.cancel();
                                        timer.purge();

                                        finish();
                                    }
                                }
                            });

                        }
                    }).
                    show();

        }
        super.onBackPressed();
    }

}
    